'use strict';
const Service = require('egg').Service;
const { Op, fn, col } = require('sequelize');

class ContractService extends Service {
  /* -----------------增----------------- */
  // 添加新的合同申请单
  async addApplication(body) {
    const { ctx } = this;
    try {
      const Application = await ctx.model.Contract.Application.create({
        ...body,
      });
      return Application;
    } catch (error) {
      console.log(error);
      ctx.throw('合同号申请失败');
    }
  }
  // 添加合同
  async addContract({ allow, id }) {
    const { ctx } = this;
    let result = '';
    const transaction = await ctx.model.transaction();
    try {
      for (let i = 0; i < allow; i++) {
        const contract = await ctx.model.Contract.Contract.create({
          application_id: id,
        });
        i === allow - 1
          ? (result += contract.id)
          : (result += contract.id + ';');
      }
      transaction.commit();
      return result;
    } catch (error) {
      console.log(error);
      transaction.rollback();
    }
  }
  // 新增产品
  async addProduct({ id, ...info }) {
    const { ctx } = this;
    try {
      const product = await ctx.model.Contract.Product.create({
        name: info.product_name,
        num: info.product_num,
        price: info.product_price,
        contract_id: id,
      });
      return product;
    } catch (error) {
      console.log(error);
      ctx.throw('创建失败');
    }
  }
  // 新增付款
  async addPay({ contract_id, ...body }) {
    const { ctx } = this;
    const transaction = await ctx.model.transaction();
    try {
      await ctx.model.Contract.Flowsheet.create({
        ...body,
        contract_id,
      });
      const contract = await ctx.model.Contract.Contract.findOne({
        where: {
          id: contract_id,
        },
        raw: true,
      });
      body.money += contract.paid;

      await ctx.model.Contract.Contract.update(
        {
          paid: body.money,
          state: contract.money === body.money ? 3 : 2,
        },
        {
          where: {
            id: contract_id,
          },
        }
      );
      transaction.commit();
      return '付款成功';
    } catch (error) {
      console.log(error);
      transaction.rollback();
      ctx.throw('付款失败');
    }
  }
  /* -------- ---------删----------------- */
  /* -----------------改----------------- */
  // 审核合同申请单
  async editApplication({ id, ...info }) {
    const { ctx } = this;
    try {
      const result = await ctx.model.Contract.Application.update(
        {
          ...info,
        },
        {
          where: {
            id,
          },
        }
      );
      if (result[0] > 0) {
        return '合同申请单修改成功';
      }
      return '修改失败';
    } catch (error) {
      console.log(error);
      ctx.throw('修改失败');
    }
  }
  // 细化合同
  async detailContract({ id, ...info }) {
    const { ctx } = this;
    try {
      const res = await ctx.model.Contract.Contract.update(
        {
          ...info,
          state: 1,
        },
        {
          where: {
            id,
          },
        }
      );
      if (res[0] > 0) {
        return '修改成功';
      }
    } catch (error) {
      ctx.throw('修改失败');
    }
  }

  // 审批合同
  async examineContract({ id, state, examine_info }) {
    const { ctx } = this;
    try {
      await ctx.model.Contract.Contract.update(
        {
          state,
          examine_info,
        },
        {
          where: { id },
        }
      );
      return '审核成功';
    } catch (error) {
      ctx.throw('审核失败');
    }
  }
  /* -----------------查----------------- */
  // 模糊查询合同
  async fuzzyToContract({ name, from, to, ...info }) {
    const { ctx } = this;
    try {
      const beforeList = await ctx.service.customer.customer.fuzzyToCustomer({
        name,
      });
      const List = [];
      beforeList.map(function (item) {
        List.push(item.id);
        return item;
      });
      const result = await ctx.model.Contract.Contract.findAll({
        where: {
          customer_id: {
            [Op.in]: List,
          },
          starttime: {
            [Op.between]: [from || '1999-01-01', to || '3000-12-31'],
          },
          ...info,
        },
        raw: true,
        attributes: {
          include: [
            [
              fn('date_format', col('created_at'), '%Y-%m-%d %H:%i:%s'),
              'created_at',
            ],
            [
              fn('date_format', col('updated_at'), '%Y-%m-%d %H:%i:%s'),
              'updated_at',
            ],
          ],
        },
      });

      return result;
    } catch (error) {
      ctx.throw('查询失败');
    }
  }
}

module.exports = ContractService;
